package com.seal.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.seal.comm.utils.Page;
import com.seal.dao.BaseDaoImpl;
import com.seal.dao.IBrandDao;
import com.seal.dto.BrandDto;
import com.seal.model.Brand;

@Service("brandDaoImpl")
@Transactional(readOnly = true)
public class BrandDaoImpl extends BaseDaoImpl implements IBrandDao {

	public void addBrand(Brand ca) throws Exception {
		this.save(ca);
	}

	public void updateBrand(Brand ca) throws Exception {
		this.update(ca);
	}

	public void deleteBrand(Brand ca) throws Exception {
		this.delete(ca);
	}

	public Brand getBrandById(Long id) throws Exception {
		return (Brand) this.select(Brand.class, id);
	}

	public List<Brand> getAllBrand(BrandDto brandDto, Page page)
			throws Exception {
		StringBuffer hql = new StringBuffer("from Brand t where 1=1 ");

		if (brandDto.getCompanyId() != null) {
			hql.append(" and t.companyId = :companyId");
		}
		
		if (brandDto.getStatus() != null) {
			hql.append(" and t.status = :status");
		}
		
		if (brandDto.getCheckflag() != null) {
			hql.append(" and t.checkflag = :checkflag");
		}

		if (null != brandDto.getBrandName()
				&& !"".equals(brandDto.getBrandName())) {
			hql.append(" and t.brandName like :brandName");
		}

		Query query = this.getSession().createQuery(hql.toString());
		query.setProperties(brandDto);
		if (null != page) {
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getPageSize());
			String countSql = "select count(t) " + hql.toString();

			Query queryCount = this.getSession().createQuery(countSql);
			queryCount.setProperties(brandDto);
			page.setTotalNumber(Integer.parseInt(queryCount.uniqueResult()
					.toString()));
		}
		return query.list();
	}
}
